package com.insist.service.impl;

import com.insist.dao.AccountFlowDao;
import com.insist.dao.ChargeDao;
import com.insist.entity.AccountFlowInfo;
import com.insist.entity.ChargeInfo;
import com.insist.entity.UserInfo;
import com.insist.enums.CmmNoType;
import com.insist.service.ChargeService;
import com.insist.service.UserService;
import com.insist.util.CmmUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by INSIST on 2016/7/2.
 */
@Service
public class ChargeServiceImpl implements ChargeService {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private ChargeDao chargeDao;
    @Autowired
    private UserService userService;
    @Autowired
    AccountFlowDao accountFlowDao;

    @Override
    public ChargeInfo createChargeOrder(Long loginUserId, Double amount) {
        ChargeInfo chargeInfo = new ChargeInfo();
        chargeInfo.setUserId(loginUserId);
        chargeInfo.setPayNo(CmmUtils.createOrderNo(CmmNoType.CHARGE));
        chargeInfo.setAmount(amount);
        chargeInfo.setState(1);
        chargeInfo.setCreateTime(new Date());
        return chargeDao.save(chargeInfo);
    }

    @Override
    public List<ChargeInfo> findChargeOrder(Long loginUserId) {
        return chargeDao.findByUserIdAndState(loginUserId, 2);
    }

    @Override
    public void updateUserInfo(String transactionId, String transactionFee,String channelType) {
        ChargeInfo chargeInfo = chargeDao.getByPayNo(transactionId);
        if(chargeInfo==null){
            logger.warn("webhook订单号不存在："+transactionId);
            return;
        }
        if(Double.valueOf(chargeInfo.getAmount()*100).intValue() != Integer.valueOf(transactionFee).intValue()){
            logger.warn("webhook金额不匹配："+chargeInfo.getAmount()+"-"+transactionFee);
            return;
        }
        chargeInfo.setState(2);
        chargeDao.save(chargeInfo);
        UserInfo userInfo = userService.getById(chargeInfo.getUserId());
        userInfo.setAccount(userInfo.getAccount()+chargeInfo.getAmount()*100);
        userService.save(userInfo);

        AccountFlowInfo accountFlowInfo2 = new AccountFlowInfo();
        accountFlowInfo2.setBizId(chargeInfo.getId());
        accountFlowInfo2.setUserId(userInfo.getId());
        accountFlowInfo2.setCreateTime(new Date());
        accountFlowInfo2.setMessage(getChargeType(channelType));
        accountFlowInfo2.setType(1);
        accountFlowInfo2.setMoney(chargeInfo.getAmount() * 100);
        accountFlowDao.save(accountFlowInfo2);

    }

    @Override
    public String getMaxOrderNo() {
        return chargeDao.getMaxOrderNo();
    }

    private String getChargeType(String channelType) {
        switch (channelType){
            case "WX":return "微信";
            case "ALI":return "支付宝";
        }
        return "系统赠送";
    }
}
